import pygame

# 所有按钮对象的列表
button_group = []


class Button:
    def __init__(self, text='按钮', left=0, top=0, width=90, height=30, color=(200, 200, 200)):
        self.text = text
        self.color = color
        self.rect = pygame.Rect(left, top, width, height)
        self.font = pygame.font.Font(r"C:\Windows\Fonts\simsun.ttc", 16)
        self.text_surface = self.font.render(self.text, True, (0, 0, 0))
        self.text_rect = self.text_surface.get_rect()
        # self.text_rect.center = self.rect.center
        self.active = False
        self.function = None
        button_group.append(self)

    def set_text(self, new_text):
        self.text = new_text
        self.text_surface = self.font.render(self.text, True, (0, 0, 0))
        self.text_rect = self.text_surface.get_rect()

    def draw(self, screen):
        if self.active:
            pygame.draw.rect(screen, (180, 180, 200), self.rect, 0)
        else:
            pygame.draw.rect(screen, self.color, self.rect, 0)
        self.text_rect.center = self.rect.center
        screen.blit(self.text_surface, self.text_rect)

    def get_click(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                mx, my = event.pos
                if self.rect.left <= mx <= self.rect.right and self.rect.top <= my <= self.rect.bottom:
                    self.active = True
        elif event.type == pygame.MOUSEBUTTONUP and self.active:
            if event.button == 1:
                mx, my = event.pos
                if self.rect.left <= mx <= self.rect.right and self.rect.top <= my <= self.rect.bottom:
                    # print(f'{self.text}按钮被点击')
                    if callable(self.function):
                        self.function()
                self.active = False

    def click_connect(self, function):
        self.function = function
